package com.fanketly.musicdiary.data.repository

import android.util.Log
import com.fanketly.musicdiary.data.TAG
import com.fanketly.musicdiary.data.db.MusicDao
import com.fanketly.musicdiary.data.model.MusicModel
import com.fanketly.musicdiary.data.network.RetrofitNetwork
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.single
import javax.inject.Inject
import javax.inject.Singleton


@Singleton
class MusicRepo @Inject constructor(
    private val musicDao: MusicDao,
    private val network: RetrofitNetwork
) {

    fun getAll(): Flow<List<MusicModel>> = musicDao.getAll()

    /**
     *网络请求音乐数据，判断id是否相同，不相同就插入，如果插入失败则说明数据库中有该id的音乐，则直接返回该音乐数据
     **/
    suspend fun update(mood: String): String? {
        return network.getMusicInfo(mood)
            .catch {
                // TODO: 添加提示
                Log.i(TAG, "update: ${it.message}")
                emit(null)
            }.map {
                if (it != null) com.lzx.starrysky.SongInfo(
                    it.songId,
                    it.songUrl,
                    it.songName,
                    it.artist,
                    it.songCover
                ) else null
            }.single()?.also {
                Log.i(TAG, "update: ${it.songId}")
                musicDao.insert(MusicModel(it, it.songId))
            }?.songId
    }

}